const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors')
const jwt = require("koa-jwt")
const { SECRET } = require("./config/secret")

require("dotenv").config();

// 导入路由
const forum = require('./routes/forumRoute') // 论坛
const user = require('./routes/userRoute') // 用户
const home = require("./routes/homeRoute") // 首页
const release = require("./routes/releaseRoute") // 发布
const petdetails = require("./routes/petDetailsRoute") // 宠物详情
const category = require("./routes/categoryRoute") // 宠物分类
const my = require("./routes/myRoute") // 我的页面
const upload = require("./routes/uploadsRoute") // 上传
const adopt = require("./routes/adoptRoute") // 领养
const contacts = require("./routes/contactsRoute") // 联系人

// error handler
onerror(app)

// 使用koa-jwt插件来拦截客户端在调用服务端接口时，如果请求头中没有设置token，返回401
// app.use(function (ctx, next) {
//   return next().catch((err) => {
//     if (401 == err.status) {
//       ctx.status = 401;
//       ctx.body = 'Protected resource, use Authorization header to get access\n';
//     } else {
//       throw err;
//     }
//   });
// });

// 设置哪些接口需要token
// jwt(加密信息) 加密信息一定要跟token生成使用加密字符串保持一致
// unless 排除哪些不需要在请求带token
// app.use(jwt({ secret: SECRET }).unless({ path: [/^\/public/, /^\/register/, /^\/login/] }));

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public/uploads'))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(cors());

// routes
app.use(forum.routes(), forum.allowedMethods())
app.use(user.routes(), user.allowedMethods())
app.use(home.routes(), home.allowedMethods())
app.use(release.routes(), release.allowedMethods())
app.use(petdetails.routes(), petdetails.allowedMethods())
app.use(category.routes(), category.allowedMethods())
app.use(my.routes(), my.allowedMethods())
app.use(upload.routes(), upload.allowedMethods())
app.use(adopt.routes(), adopt.allowedMethods())
app.use(contacts.routes(), contacts.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
